package com.engc.common.utils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;



public class PageUtils {
	private static ThreadLocal<Integer> page = new ThreadLocal<Integer>();
	private static ThreadLocal<Integer> pagesize = new ThreadLocal<Integer>();
	
	private static ThreadLocal<String >sortname = new ThreadLocal<String>();
	private static ThreadLocal<String> sortorder = new ThreadLocal<String>();
	private static ThreadLocal<String> where = new ThreadLocal<String>();
	private static ThreadLocal<Object[]> parameter = new ThreadLocal<Object[]>();
	private PageUtils(){
		
	}
	public static void Load(HttpServletRequest request){
		if(request.getParameter("page")!=null&&!"".equals(request.getParameter("page"))){
			page.set(Integer.valueOf(request.getParameter("page")));
		}
		if(request.getParameter("pagesize")!=null&&!"".equals(request.getParameter("pagesize"))){
			pagesize.set(Integer.valueOf(request.getParameter("pagesize")));
		}
		if(request.getParameter("sortname")!=null&&!"".equals(request.getParameter("sortname"))){
			sortname.set(request.getParameter("sortname")); 
		}
		sortorder.set(request.getParameter("sortorder"));
		where.set(request.getParameter("where"));
	}
	public static void remove(){
		page.remove();
		pagesize.remove();
		sortname.remove();
		sortorder.remove();
		where.remove();
		parameter.remove();
	}
	
	
	public static int getPage(){
		Integer intvalue = (Integer)page.get();
		if(intvalue==null){
			intvalue = 0;
		}
		return intvalue;
	}
	
	public static int getPagesize(){
		Integer intvalue = (Integer)pagesize.get();
		if(intvalue==null){
			intvalue = 0; 
		}
		return intvalue;
	}
	
	public static String getwheresql(String alias) throws Exception{
		String wheres = where.get();
		String sql = " 1=1 ";
		if(wheres!=null&&!"".equals(wheres)){
			FilterGroup where = JSON.parseObject(wheres, FilterGroup.class);
			FilterTranslator translator = new FilterTranslator(where);
			alias = "".equals(alias)||alias==null?"":alias;
			alias = !"".equals(alias)&&!alias.contains(".")?alias+".":alias;
			sql = translator.TranslateGroup(where,alias);
			parameter.set(translator.getParameters());
		}
		return sql;
	}
	
	public static Map getFilter() throws Exception{
		String wheres = where.get();
		Map filter = new HashMap();
		if(wheres!=null&&!"".equals(wheres)){
			FilterGroup where = JSON.parseObject(wheres, FilterGroup.class);
			List<rule> rulelst = where.getRules();
			for(rule rule:rulelst){
				filter.put(rule.getField(), rule.getValue());
			}
		}
		return filter;
	}
	
	public static Object[] getwhereParameter(){
		return parameter.get();
	}
}
